// city-group-bar.ts
import { Ref } from 'vue';

export interface GroupOrder {
  orderNum: number;
  groupName: string;
  totalAmount: number;
}

export interface CityData {
  city: string;
  groupOrders: GroupOrder[];
  orderNum: number;
  totalAmount: number;
}

/**
 * 将接口数据转成 ECharts 配置
 * @param echartRef  绑定的 DOM
 * @param raw        后端原始数组 CityData[]
 * @param valueKey   用哪个字段作为柱子高度：'orderNum' | 'totalAmount'
 */
export default function initCityBar(
  echartRef: Ref<null>,
  raw: CityData[],
  valueKey: 'orderNum' | 'totalAmount' = 'orderNum'
) {
  if (!raw?.length) return;

  const chart = window.echarts.init(echartRef.value);

  /* ---------- 1. 收集所有可能的分组名 ---------- */
  const groupSet = new Set<string>();
  raw.forEach(c => c.groupOrders.forEach(g => groupSet.add(g.groupName)));
  const groups = Array.from(groupSet); // ['优选区','定制','孵化区'...]

  /* ---------- 2. 构造 series ---------- */
  const series = groups.map(groupName => ({
    name: groupName,
    type: 'bar',
    stack: 'total',
    barWidth: '40%',
    label: { show: false },
    data: raw.map(cityItem => {
      const hit = cityItem.groupOrders.find(g => g.groupName === groupName);
      return hit ? hit[valueKey] : 0;
    }),
  }));

  /* ---------- 3. 构造 option ---------- */
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any) => {
        let tip = `<div>${params[0].axisValue}</div>`;
        params.forEach((p: any) => {
          tip += `<div style="display:flex;justify-content:space-between">
                    <span style="margin-right:16px">${p.seriesName}</span>
                    <span>${p.value}</span>
                  </div>`;
        });
        return tip;
      },
    },
    legend: { data: groups ,show:false},
    grid: { left: 10, top: 10, right: 10, bottom: 20 },
    xAxis: { type: 'category', data: raw.map(c => c.city) },
    yAxis: { type: 'value', name: valueKey === 'orderNum' ? '订单数' : '金额(元)' },
    series,
  };
  chart.setOption(option);
}